<template>
    <div class="welcome">
        <HeaderBar />

        <div class="operation-bar">
            <h2 class="page-title">API密钥管理</h2>
            <div class="right-operations">
                <el-input placeholder="请输入密钥名称查询" v-model="searchName" class="search-input"
                    @keyup.enter.native="handleSearch" clearable />
                <el-button class="btn-search" @click="handleSearch">搜索</el-button>
                <el-button class="btn-add" @click="addApiKey">新增</el-button>
            </div>
        </div>

        <div class="main-wrapper">
            <div class="content-panel">
                <div class="content-area">
                    <el-card class="apikey-card" shadow="never">
                        <el-table ref="apiKeyTable" :data="apiKeyList" class="transparent-table" v-loading="loading"
                            element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                            element-loading-background="rgba(255, 255, 255, 0.7)"
                            :header-cell-class-name="headerCellClassName">
                            <el-table-column label="选择" align="center" width="60">
                                <template slot-scope="scope">
                                    <el-checkbox v-model="scope.row.selected"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column label="密钥名称" prop="keyName" align="center"></el-table-column>
                            <el-table-column label="API密钥" prop="apiKey" align="center" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span v-if="!scope.row.showKey">{{ maskApiKey(scope.row.apiKey) }}</span>
                                    <span v-else>{{ scope.row.apiKey }}</span>
                                    <el-button size="mini" type="text" @click="toggleApiKey(scope.row)">
                                        {{ scope.row.showKey ? '隐藏' : '查看' }}
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="权限等级" prop="permissionLevel" align="center">
                                <template slot-scope="scope">
                                    <el-tag v-if="scope.row.permissionLevel === 1" type="danger">Admin</el-tag>
                                    <el-tag v-else-if="scope.row.permissionLevel === 2" type="warning">High</el-tag>
                                    <el-tag v-else-if="scope.row.permissionLevel === 3" type="primary">Medium</el-tag>
                                    <el-tag v-else-if="scope.row.permissionLevel === 4" type="success">Public</el-tag>
                                    <span v-else>{{ scope.row.permissionLevel }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" prop="status" align="center">
                                <template slot-scope="scope">
                                    <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
                                    <el-tag v-else type="danger">停用</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="过期时间" prop="expireDate" align="center"></el-table-column>
                            <el-table-column label="备注" prop="remark" align="center"></el-table-column>
                            <el-table-column label="创建时间" prop="createDate" align="center"></el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="text" @click="editApiKey(scope.row)">编辑</el-button>
                                    <el-button size="mini" type="text" @click="deleteApiKey(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="table_bottom">
                            <div class="ctrl_btn">
                                <el-button @click="batchDelete" :disabled="!hasSelected">批量删除</el-button>
                            </div>
                            <div class="page_ctrl">
                                <el-pagination @current-change="handlePageChange" :current-page="currentPage"
                                    :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper">
                                </el-pagination>
                            </div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>

        <!-- 新增/编辑API密钥对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="handleDialogClose">
            <el-form :model="currentApiKey" :rules="rules" ref="apiKeyForm" label-width="100px">
                <el-form-item label="密钥名称" prop="keyName">
                    <el-input v-model="currentApiKey.keyName" placeholder="请输入密钥名称"></el-input>
                </el-form-item>
                <el-form-item label="权限等级" prop="permissionLevel">
                    <el-select v-model="currentApiKey.permissionLevel" placeholder="请选择权限等级">
                        <el-option label="Admin" :value="1"></el-option>
                        <el-option label="High" :value="2"></el-option>
                        <el-option label="Medium" :value="3"></el-option>
                        <el-option label="Public" :value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="过期时间" prop="expireDate">
                    <el-date-picker v-model="currentApiKey.expireDate" type="datetime" placeholder="请选择过期时间"
                        value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="currentApiKey.remark" type="textarea" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveApiKey">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 查看API密钥对话框 -->
        <el-dialog title="API密钥详情" :visible.sync="detailDialogVisible" width="500px">
            <el-form label-width="100px">
                <el-form-item label="API密钥：">
                    <el-input v-model="currentApiKey.apiKey" readonly>
                        <el-button slot="append" icon="el-icon-document-copy" @click="copyApiKey">复制</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="密钥名称：">
                    <el-input v-model="currentApiKey.keyName" readonly></el-input>
                </el-form-item>
                <el-form-item label="权限等级：">
                    <el-input v-model="permissionLevelText" readonly></el-input>
                </el-form-item>
                <el-form-item label="过期时间：">
                    <el-input v-model="currentApiKey.expireDate" readonly></el-input>
                </el-form-item>
                <el-form-item label="备注：">
                    <el-input v-model="currentApiKey.remark" type="textarea" readonly></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import HeaderBar from '@/components/HeaderBar.vue';
import Api from '@/apis/api.js';

export default {
    name: 'ApiKeyManagement',
    components: {
        HeaderBar
    },
    data() {
        return {
            searchName: '',
            apiKeyList: [],
            loading: false,
            currentPage: 1,
            pageSize: 10,
            total: 0,
            dialogVisible: false,
            detailDialogVisible: false,
            dialogTitle: '',
            isEdit: false,
            currentApiKey: {
                id: null,
                keyName: '',
                apiKey: '',
                permissionLevel: 3, // 默认为Medium权限
                status: 1,
                expireDate: '',
                remark: ''
            },
            rules: {
                keyName: [
                    { required: true, message: '请输入密钥名称', trigger: 'blur' }
                ],
                permissionLevel: [
                    { required: true, message: '请选择权限等级', trigger: 'change' }
                ]
            }
        }
    },
    computed: {
        hasSelected() {
            return this.apiKeyList.some(item => item.selected);
        },
        permissionLevelText() {
            const level = this.currentApiKey.permissionLevel;
            switch (level) {
                case 1: return 'Admin';
                case 2: return 'High';
                case 3: return 'Medium';
                case 4: return 'Public';
                default: return '';
            }
        }
    },
    mounted() {
        this.fetchApiKeys();
    },
    methods: {
        headerCellClassName({ row, column, rowIndex, columnIndex }) {
            return 'table-header';
        },
        fetchApiKeys() {
            this.loading = true;
            Api.admin.getApiKeyList(
                {
                    page: this.currentPage,
                    limit: this.pageSize,
                    keyName: this.searchName
                },
                ({ data }) => {
                    this.loading = false;
                    if (data.code === 0) {
                        this.apiKeyList = data.data.list.map(item => ({
                            ...item,
                            selected: false,
                            showKey: false
                        }));
                        this.total = data.data.total;
                    } else {
                        // 显示具体的错误信息
                        this.$message.error(data.msg || '获取API密钥列表失败');
                        // 如果是权限问题，跳转到首页
                        if (data.code === 401 || data.code === 403) {
                            this.$router.push('/home');
                        }
                    }
                }
            );
        },
        handleSearch() {
            this.currentPage = 1;
            this.fetchApiKeys();
        },
        handlePageChange(page) {
            this.currentPage = page;
            this.fetchApiKeys();
        },
        addApiKey() {
            this.dialogTitle = '新增API密钥';
            this.isEdit = false;
            this.currentApiKey = {
                id: null,
                keyName: '',
                apiKey: '',
                permissionLevel: 3,
                status: 1,
                expireDate: '',
                remark: ''
            };
            this.dialogVisible = true;
        },
        editApiKey(row) {
            this.dialogTitle = '编辑API密钥';
            this.isEdit = true;
            this.currentApiKey = { ...row };
            this.dialogVisible = true;
        },
        saveApiKey() {
            this.$refs.apiKeyForm.validate((valid) => {
                if (valid) {
                    if (this.isEdit) {
                        // 编辑API密钥
                        Api.admin.updateApiKey(this.currentApiKey, ({ data }) => {
                            if (data.code === 0) {
                                this.$message.success('API密钥更新成功');
                                this.dialogVisible = false;
                                this.fetchApiKeys();
                            } else {
                                this.$message.error(data.msg || '更新失败');
                            }
                        });
                    } else {
                        // 新增API密钥
                        Api.admin.createApiKey(this.currentApiKey, ({ data }) => {
                            if (data.code === 0) {
                                this.$message.success('API密钥创建成功');
                                this.dialogVisible = false;
                                this.fetchApiKeys();
                            } else {
                                this.$message.error(data.msg || '创建失败');
                            }
                        });
                    }
                }
            });
        },
        deleteApiKey(row) {
            this.$confirm('确定要删除该API密钥吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                Api.admin.deleteApiKey([row.id], ({ data }) => {
                    if (data.code === 0) {
                        this.$message.success('删除成功');
                        this.fetchApiKeys();
                    } else {
                        this.$message.error(data.msg || '删除失败');
                    }
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        batchDelete() {
            const selectedKeys = this.apiKeyList.filter(item => item.selected);
            if (selectedKeys.length === 0) {
                this.$message.warning('请先选择要删除的API密钥');
                return;
            }

            const ids = selectedKeys.map(item => item.id);

            this.$confirm(`确定要删除选中的${ids.length}个API密钥吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                Api.admin.deleteApiKey(ids, ({ data }) => {
                    if (data.code === 0) {
                        this.$message.success('删除成功');
                        this.fetchApiKeys();
                    } else {
                        this.$message.error(data.msg || '删除失败');
                    }
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        toggleApiKey(row) {
            // 只有在查看详细信息时才显示完整API密钥
            if (!row.showKey) {
                // 先获取完整的API密钥信息
                Api.admin.getApiKey(row.id, ({ data }) => {
                    if (data.code === 0) {
                        row.apiKey = data.data.apiKey;
                        row.showKey = !row.showKey;
                        
                        // 显示详情对话框
                        this.currentApiKey = { ...data.data };
                        this.detailDialogVisible = true;
                    }
                });
            } else {
                row.showKey = !row.showKey;
            }
        },
        maskApiKey(apiKey) {
            if (!apiKey) return '';
            if (apiKey.length <= 8) return '********';
            return apiKey.substring(0, 4) + '****' + apiKey.substring(apiKey.length - 4);
        },
        copyApiKey() {
            const text = this.currentApiKey.apiKey;
            navigator.clipboard.writeText(text).then(() => {
                this.$message.success('API密钥已复制到剪贴板');
            }).catch(() => {
                this.$message.error('复制失败');
            });
        },
        handleDialogClose() {
            this.$refs.apiKeyForm.resetFields();
        }
    }
}
</script>

<style lang="scss" scoped>
@import './auth.scss';

.welcome {
    min-width: 900px;
    min-height: 506px;
    height: 100vh;
    display: flex;
    position: relative;
    flex-direction: column;
    background-size: cover;
    background: linear-gradient(to bottom right, #dce8ff, #e4eeff, #e6cbfd) center;
    -webkit-background-size: cover;
    -o-background-size: cover;
    overflow: hidden;
}

.main-wrapper {
    margin: 5px 22px;
    border-radius: 15px;
    min-height: calc(100vh - 24vh);
    height: auto;
    max-height: 80vh;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    position: relative;
    background: rgba(237, 242, 255, 0.5);
    display: flex;
    flex-direction: column;
}

.operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    margin-top: 10px;

    .page-title {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin: 0;
    }

    .right-operations {
        display: flex;
        align-items: center;
        gap: 10px;

        .search-input {
            width: 250px;
        }

        .btn-search,
        .btn-add {
            padding: 8px 16px;
        }
    }
}

.content-panel {
    flex: 1;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .content-area {
        flex: 1;
        overflow-y: auto;
        padding: 10px;

        .apikey-card {
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            .transparent-table {
                background: transparent;

                ::v-deep .el-table__header th {
                    background-color: #f5f7fa;
                }
            }
        }
    }
}

.table_bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;

    .ctrl_btn {
        .el-button {
            margin-right: 10px;
        }
    }

    .page_ctrl {
        display: flex;
        justify-content: flex-end;
    }
}

.dialog-footer {
    text-align: right;
}
</style>